#!/usr/bin/python3.6
# -*- encoding: UTF-8 -*-
import requests
import os,json,datetime,time

def prometheus_alarm():
    user = 'admin'
    password = 'xx'
    #nodeurl = 'https://prome-cn1.dvr163.com/api/v1/alerts'
    appurl = 'https://alert.dvr163.com/api/v2/alerts'
    #noderesult=requests.get(nodeurl,auth=(user, password)).json()
    appresult=requests.get(appurl,auth=(user, password)).json()

    file_dir = "/usr/local/shell/alter/readfile/"
    alter_file = file_dir+"source.log"
    os.system('>{}'.format(alter_file))
    getValue(appresult,alter_file)
    #习惯用shell做文件处理了,方便一点
    os.system('/bin/bash  /usr/local/shell/alter/shell/alarmProcess.sh')

def getValue(prometheus_result,alter_file):
    #print(prometheus_result)
    #for valueLine in prometheus_result['data']['alerts']:
    for valueLine in prometheus_result:
        #主题,主机,等级,描述,时间,值
        alertname = valueLine['labels']['alertname']
        hostname = valueLine['labels']['hostname']
        severity = valueLine['labels']['severity']
        description, description_value  = valueLine['annotations']['description'].split("\n")
        description_value = description_value.split(' ')[-1]
        fingerprint = valueLine['fingerprint']
        activeAt =  valueLine['startsAt']
        os.system('echo "{}￥{}￥{}￥{}￥{}￥{}￥{}" >>{}'.format(activeAt,alertname,hostname,severity,description,description_value,fingerprint,alter_file))

prometheus_alarm()